package com.onenine.app.activity;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Pair;
import android.util.SparseBooleanArray;
import android.view.View;

import com.onenine.app.R;
import com.onenine.app.adapter.MemberSelectAdapter;
import com.onenine.app.event.MessageNotifyEvent;
import com.onenine.app.event.RefreshEvent;
import com.onenine.app.fragment.FriendAttentionFragment;
import com.onenine.app.model.MemberItem;
import com.onenine.app.request.GroupCreateRequest;
import com.onenine.app.request.PageRequest;
import com.onenine.app.response.FriendAttentionResponse;
import com.onenine.app.response.GroupCreateResponse;
import com.onenine.app.utils.CDataProcessor;
import com.onenine.app.utils.DataType;
import com.onenine.app.utils.RoleResLoader;
import com.onenine.app.utils.UrlConfig;
import com.onenine.base.base.BasePageListActivity;
import com.onenine.base.okhttp.OkCallback;
import com.onenine.base.okhttp.OkRequest;
import com.onenine.base.utils.AppConfig;
import com.onenine.base.utils.Toasty;
import com.onenine.base.view.PullRefreshRecyclerView;
import com.onenine.chat.rongcloud.RcUser;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * 创建群聊
 */
public class GroupCreateActivity extends BasePageListActivity {

    private List<MemberItem> mDataList = new ArrayList<>();

    @Override
    protected int getLayout() {
        return R.layout.activity_pull_refresh_layout;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void initViews() {
        super.initViews();
        mToolbar.setRightTextVisible(false);
        mToolbar.setLeftTitle(R.string.cancel);
        mToolbar.setCenterTitle(R.string.select_friend);
        mToolbar.setRightTitle(R.string.create);
        mToolbar.setRightTitleBackground(RoleResLoader
                .getRoleDrawableResourceId(RoleResLoader.DynamicResName.THEME_GRADIENT_CORNER_BG), true);
    }

    @Override
    protected Pair<PullRefreshRecyclerView, RecyclerView.Adapter> initPullRefreshView() {
        return new Pair(findViewById(R.id.pull_to_refresh_layout), new MemberSelectAdapter(mDataList));
    }

    @Override
    protected void loadPageData(int pageNum) {
        PageRequest request = new PageRequest();
        request.setUserId(RcUser.getInstance().getUserId());
        request.setPageNum(pageNum);
        request.setPageSize(AppConfig.PAGE_SIZE);
        OkRequest.getInstance().withUrl(UrlConfig.GET_FRIEND_LIST).withRequest(request)
                .doRequest(FriendAttentionFragment.class.getSimpleName(), new OkCallback<FriendAttentionResponse>() {
                    @Override
                    public void onResponse(FriendAttentionResponse response, String srcData) {
                        dismissRefreshStatus();
                        if (response.isSuccess()) {
                            notifyDataSuccess(response.getDataList());
                        } else {
                            notifyDataFailure();
                        }
                    }
                });
    }

    @Override
    protected void initData() {
        super.initData();
        loadPageData(1);
    }

    @Override
    protected void resetPagePullRefresh() {
        super.resetPagePullRefresh();
        mToolbar.setRightTextVisible(false);
        mToolbar.setRightTitle("");
        ((MemberSelectAdapter) mAdapter).clearSelectArray();
    }

    @Override
    protected void initListeners() {
        super.initListeners();
        mToolbar.setOnRightClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Pair<String, String> userInfos = getUserInfos();
                if (userInfos.first.split(",").length <= 1) {
                    //直接1对1聊天
                    PrivateMessageActivity.launchActivity(GroupCreateActivity.this
                            , userInfos.first, userInfos.second);
                    finish();
                } else {
                    //创建群聊
                    reqGroupCreate(userInfos);
                }
            }
        });
    }

    /**
     * 创建群聊
     */
    private void reqGroupCreate(final Pair<String, String> idNames) {
        showLoading(R.string.submit_data_doing);
        GroupCreateRequest request = new GroupCreateRequest();
        request.setUserId(RcUser.getInstance().getUserId());
        request.setJoinUserId(idNames.first);
        OkRequest.getInstance().withUrl(UrlConfig.CREATE_GROUP_CHAT)
                .withRequest(request)
                .doRequest(GroupMessageActivity.class.getSimpleName(), new OkCallback<GroupCreateResponse>() {
                    @Override
                    public void onResponse(GroupCreateResponse response, String srcData) {
                        dismissLoading();
                        if (response.isSuccess() && !TextUtils.isEmpty(response.getGroupChatId())) {
                            if (isFinishing()) {
                                return;
                            }
                            CDataProcessor.insertGroupCreateNotificationMessage(response.getGroupChatId()
                                    , getString(R.string.group_create_event_msg, idNames.second));
                            EventBus.getDefault().post(new MessageNotifyEvent(DataType.COMMON_NOTIFY_MSG));
                            GroupMessageActivity.launchActivity(GroupCreateActivity.this
                                    , response.getGroupChatId(), getResources().getString(R.string.group_chat));
                            finish();
                        } else {
                            Toasty.showNormal(response.getMessage());
                        }
                    }
                });
    }

    /**
     * 拼接人员id或姓名
     *
     * @return
     */
    private Pair<String, String> getUserInfos() {
        SparseBooleanArray mSelectArray = ((MemberSelectAdapter) mAdapter).getSelectArray();
        StringBuilder userIds = new StringBuilder();
        StringBuilder userNames = new StringBuilder();
        for (int i = 0; i < mSelectArray.size(); i++) {
            if (mSelectArray.valueAt(i)) {
                MemberItem groupMember = mDataList.get(mSelectArray.keyAt(i));
                userIds.append(groupMember.getUserId()).append(",");
                userNames.append(groupMember.getNickName()).append("、");
            }
        }
        if (userIds.toString().endsWith(",")) {
            userIds.deleteCharAt(userIds.length() - 1);
        }
        if (userNames.toString().endsWith("、")) {
            userNames.deleteCharAt(userNames.length() - 1);
        }
        return Pair.create(userIds.toString(), userNames.toString());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(RefreshEvent event) {
        if (event.type == DataType.REFRESH_MEMBER_SELECT_COUNT) {
            if (event.extraInt > 0) {
                mToolbar.setRightTextVisible(true);
                mToolbar.setRightTitle(String.format("确定(%d)", event.extraInt));
            } else {
                mToolbar.setRightTextVisible(false);
                mToolbar.setRightTitle("");
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

}
